<?php

namespace app\services;

use app\traits\Page;
use plugin\admin\app\model\GoodsComment;
use plugin\admin\app\model\GoodsCommentReply;
use plugin\admin\app\model\GoodsSKU;
use plugin\admin\app\model\Order;
use plugin\admin\app\model\OrderGoods;
use plugin\admin\app\model\UserProfile;

class GoodsCommentService
{
    public static function comment($orderNo, $comments, $anonymous)
    {
        $orderInfo = Order::where('order_no', $orderNo)->first();

        if (!$orderInfo) {
            throw new \Exception('不存在的订单');
        }

        if ($orderInfo['status'] != Order::STATUS_WAITING_COMMENT) {
            throw new \Exception('该订单状态不允许评价');
        }

        $orderInfo->status = Order::STATUS_FINISH;
        $orderInfo->save();

        $insertData = [];

        foreach ($comments as $comment) {
            $insertData[] = [
                'user_id' => get_user_id(),
                'order_goods_id' => $comment['goods_id'],
                'goods_id' => $comment['goods_id'] ?? 0,
                'sku_id' => $comment['sku_id'] ?? 0,
                'order_no' => $orderNo,
                'desc' => $comment['desc'],
                'service' => $comment['service'],
                'thumbs' => json_encode($comment['thumbs'], JSON_UNESCAPED_UNICODE),
                'created_time' => date('Y-m-d H:i:s'),
                'anonymous' => $anonymous ?? 0
            ];
        }

        GoodsComment::insert($insertData);
    }

    public static function goodCommentRate($goodsId)
    {
        ['all_count' => $allCount, 'good_count' => $goodCount] = self::getCommentCount($goodsId);

        if ($allCount == 0) {
            return 0;
        }

        return bcdiv($goodCount, $allCount, 3) * 100;
    }


    public static function getNiceComments($goodsId, $page = 1, $length = 10)
    {
        return self::commentList($goodsId, $page, $length, 0, function($query) {
           $query->where('is_good', 1);
        });
    }

    public static function getCommentCount($goodsId)
    {
        $hasThumbCount = GoodsComment::where('goods_id', $goodsId)->where('is_enable', 1)->whereNotNull('thumbs')->count();
        $allCount = GoodsComment::where('goods_id', $goodsId)->where('is_enable', 1)->count();
        $goodCount = GoodsComment::where('goods_id', $goodsId)->where('service', '>=', 4)->count();

        return ['all_count' => $allCount, 'thumb_count' => $hasThumbCount, 'good_count' => $goodCount];
    }

    public static function commentList($goodsId, $page = 1, $length = 10, $filterType = 0, $queryCallback = null)
    {
        $offset = ($page - 1) * $length;
        $query = GoodsComment::where('goods_id', $goodsId)->where('is_enable', 1);

        switch ($filterType) {
            case 1:
                $query = $query->whereNotNull('thumbs');    //有图
                break;
            case 3:
                $query = $query->where('service', '>=', 4); //好评
        }

        if (!is_null($queryCallback) && is_callable($queryCallback)) {
            call_user_func($queryCallback, $query);
        }

        $totalCount = (clone $query)->count();

        if ($filterType == 2) {
            $list = $query->offset($offset)->limit($length)->orderByDesc('created_time')->get()->toArray();
        } else {
            $list = $query->offset($offset)->limit($length)->get()->toArray();
        }

        $userIds = array_column($list, 'user_id');
        $users = UserProfile::select(['user_id', 'nickname', 'avatar'])->whereIn('user_id', $userIds)->get()->toArray();
        $users = array_combine(
            array_column($users, 'user_id'),
            array_values($users)
        );

        $orderGoodsIds = array_column($list, 'order_goods_id');
        $orderGoodsList = OrderGoods::whereIn('goods_id', $orderGoodsIds)->get()->toArray();
        $orderGoodsList = array_combine(
            array_column($orderGoodsList, 'goods_id'),
            array_values($orderGoodsList)
        );

        $commentIds = array_column($list, 'id');
        $reply = GoodsCommentReply::whereIn('comment_id', $commentIds)->get()->toArray();
        $reply = array_combine(
            array_column($reply, 'comment_id'),
            array_values($reply)
        );

        foreach ($list as $key=>$item) {
            $item['user_info'] = $users[$item['user_id']];
            $item['goods_info'] = $orderGoodsList[$item['order_goods_id']] ?? [];
            $item['reply_info'] = $reply[$item['id']] ?? null;
            $list[$key] = $item;
        }

        return Page::wrap($totalCount, $page, $length, $list);
    }
}